<template>
  <div class="map">
    <div id="cesiumContainer"></div>
  </div>
</template>

<script>
// 引入安定区边界数据和漫游路线数据
import andingqu from "@/js/andingqu.json";
// import manyou from "@/js/manyou.json";
// import line from "@/js/line.json";
import gsap from "gsap";
import Bus from "@/js/EventBus";
import {
  addWMSLayer,
  showOrhideWMSLayer,
  cameraFlyto,
  showOrhideBaseLayer,
  getlenLonlat,
} from "@/js/layer";
import {
  getpolyLineData,
  getpolyLineData1,
  getpolyPointData,
  getpolyxzqhData,
  getBoxPointData,
  getBoxLineData,
  getYXQYidData,
} from "@/api/http";
// 二维流向材质
// import "@/js/ImageLineMaterial";
// 三维自定义流向材质
import PolyLineTest from "@/js/PolylineTest";
// 挖方效果
// import TerrainClipPlan from "@/js/TerrainClipPlan";
// 量算
import "@/js/cesium-measure.js";
import * as turf from "@turf/turf";
import { TOKRN } from "../../../public/mapconfig";
import { addLayer, showLayer, hideLayer } from "@/js/layer1";
import { basegeoserver } from "../../../public/mapconfig";
export default {
  data() {
    return {
      viewer: null,
      primitiveList: [],
      labels: null,
      labelslist: [],
      addgxlx: false,
      addcunming: false,
      addcundian: false,
      addsltclayer: false,
      // 是否贴地
      clampToGround: true,
      // infowindow传出的数据（id）
      // infodata: null,
      // 所有管线高亮的数组
      heightColorlinesList: [],
      heightColorpointsList: null,
      heightColorpointsType: null,
      // 爆管分析暂存的数据
      bgfxData: [],
      // 缓冲区域的暂存数据
      allyxqudata: [],
      // 挖方暂存实体
      // terrainClipPlan: null,
      newpos: [],
      minheight: null,
      wellWall: null,
      bottomSurface: null,
      TerrainClipPlan: {
        height: null,
        oldpos: null,
        bottomImg: null,
        wallImg: null,
      },
      // 飞行的服务
      dataSources: null,
      entityB2: null,
      onTickEvent: null,
      guanlineliuxadd: false,
      btntype: 3,
      guanxian: [],
    };
  },
  computed: {
    maptype() {
      return this.$store.getters.maptype;
    },
    famendata() {
      return this.$store.getters.famendata;
    },
    guanxiandata() {
      return this.$store.getters.guanxiandata;
    },
    xzqhlayerdata() {
      return this.$store.getters.xzqhlayerdata;
    },
    mapstatus() {
      return this.$store.getters.mapstatus;
    },
    mapinit() {
      return this.$store.getters.mapinit;
    },
    toolbarshowhide() {
      return this.$store.getters.toolbarshowhide;
    },
    manyoudata() {
      return this.$store.getters.manyoudata;
    },
    // btntype() {
    //   return this.$store.getters.btntype;
    // },
  },
  created() {
    this.$nextTick(() => {
      this.getData(this.updateMap);
      // this.getData1();
    });
    let btntype = window.sessionStorage.getItem("btntype");
    if (btntype) {
      this.btntype = btntype;
    }
  },
  beforeDestroy() {
    // 移除事件监听器
    // Bus.$off("btntype")
    Bus.$off("layer");
    // Bus.$off("Polyline")
    // Bus.$off("Polygon")
    // Bus.$off("Height")
    // Bus.$off("Clear")
    // Bus.$off("ZoomOut")
    // Bus.$off("GoHome")
    // Bus.$off("ZoomIn")
    // Bus.$off("draw")
    // Bus.$off("initlineandpoint")
    // Bus.$off("gffx")
    // Bus.$off("ltfx")
    // Bus.$off("bgfx")
    // Bus.$off("removedraw")
    // Bus.$off("startFly3")
    // Bus.$off("exitFly3")
    // Bus.$off("addpoint")
    // Bus.$off("removepoint")
    // Bus.$off("addlinecolor")
    // Bus.$off("removealllinecolor")
    // Bus.$off("removelinecolor")
    // Bus.$off("dingwei")
    // Bus.$off("selectyxqu")
    // Bus.$off("removeyxqu")
    // Bus.$off("xiaohui")
  },
  mounted() {
    this.initMap();
    Bus.$on("btntype", (e) => {
      this.btntype = e;
    });
    Bus.$on("layer", (e) => {
      if (e[0] == null) {
        return;
      }
      this.addImagelayer(e[0], e[1]);
    });
    Bus.$on("Polyline", (e, r) => {
      // console.log(e);
      this.measureDestroy();
      this.measurePolyLine(e, r);
    });
    Bus.$on("Polygon", (e, r) => {
      this.measureDestroy();
      this.measurePolygon(e, r);
    });
    Bus.$on("Height", (e) => {
      this.measureDestroy();
      this.measureHeight();
    });
    Bus.$on("Clear", (e) => {
      this.measureDestroy();
    });
    Bus.$on("ZoomOut", (e) => {
      // console.log(e);
      this.zoomout(e);
    });
    Bus.$on("GoHome", (e) => {
      // console.log(e);
      this.gohome(e);
    });
    Bus.$on("ZoomIn", (e) => {
      // console.log(e);
      this.zoomin(e);
    });
    Bus.$on("draw", (e) => {
      // console.log(e);
      // this.zoomin(e);
      this.drawPolygon(e);
    });
    // 重置-初始化
    Bus.$on("initlineandpoint", (e) => {
      this.clearHeightColoridlist();
      this.removenewpoint();
      this.removeallyxqu();
      this.removePolygon();
      Bus.$emit("gffx", false);
      Bus.$emit("ltfx", false);
      Bus.$emit("bgfx", false);
      this.measureDestroy();
    });

    Bus.$on("removedraw", (e) => {
      this.removePolygon();
      // console.log(e);
      // this.zoomin(e);
      // this.drawPolygon(e)
    });

    Bus.$on("bgfx", (e) => {
      this.bgfx = e;
      if (e == false) {
        this.bgfxData = [];
        this.removematerialREDline();
        this.clearHeightColoridlist();
        this.removenewpoint();
      }
    });
    Bus.$on("ltfx", (e) => {
      this.ltfx = e;
      if (e == false) {
        this.clearHeightColoridlist();
        // this.clearHeightColor(this.heightColorlinesList);
      }
    });
    Bus.$on("gffx", (e, data) => {
      if (e == false) {
        this.clearHeightColoridlist();
        // this.clearpointHeightColoridlist();
        this.removenewpoint();
      } else {
      }
    });
    Bus.$on("kwfx", (e, data, height) => {
      if (e == false) {
        this.clearExcavation();
      } else {
        this.excavationAnalysis(data, height);
      }
    });
    // Bus.$on("initFly3", (data) => {
    //   console.log(data, "333333333");
    //   switch (data) {
    //     case 0:
    //       this.initFly();
    //       break;
    //     case 1:
    //       this.startFly(this.initFly);
    //       break;
    //     case 2:
    //       this.stopFly();
    //       break;
    //     case 3:
    //       this.continueFly();
    //       break;
    //     case 4:
    //       this.exitFly();
    //       break;

    //     default:
    //       break;
    //   }
    // });
    Bus.$on("startFly3", (e) => {
      this.startFly(e, this.initFly);
    });
    Bus.$on("exitFly3", (e) => {
      this.exitFly();
    });
    //  添加高亮图标
    Bus.$on("addpoint", (e) => {
      this.removenewpoint();
      this.addnewpoint(e);
    });
    //  清楚高亮图标
    Bus.$on("removepoint", (e) => {
      this.removenewpoint();
      // this.addnewpoint(e)
    });
    // 添加高亮管线
    Bus.$on("addlinecolor", (e) => {
      this.addlinesHeightColor(e);
    });
    // 清楚s所有高亮管线
    Bus.$on("removealllinecolor", (e) => {
      this.clearHeightColoridlist();
    });
    // 清楚单个高亮管线
    Bus.$on("removelinecolor", (e) => {
      let newlist = [];
      // console.log(this.heightColorlinesList, "this.heightColorlinesList");
      this.heightColorlinesList.forEach((element) => {
        if (e == element.properties.UserID) {
          newlist.push(element);
        }
      });
      this.clearHeightColor(newlist);
    });
    Bus.$on("dingwei", (e) => {
      this.dingweiFly(e);
    });
    Bus.$on("selectyxqu", (e) => {
      this.selectallyxqu1(e, true);
    });
    Bus.$on("removeyxqu", (e) => {
      this.removeallyxqu();
    });
    Bus.$on("xiaohui", (e) => {
      this.viewer.destroy();
    });
  },
  methods: {
    // 初始化地图
    initMap() {
      Cesium.Ion.defaultAccessToken =
        "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJqdGkiOiIxNmEzOGY5YS1jOGQ0LTQ0YWUtYjc5Zi1iNWNiNDQyMzliZTYiLCJpZCI6MzczOTQsImlhdCI6MTcwNTkwODA4MH0.Zcwa37fVh1PbYNzH-4LCNQBkr-XeBjUVk88fPmtIf-s";
      const viewer = (this.viewer = new Cesium.Viewer("cesiumContainer", {
        sceneMode: Cesium.SceneMode.SCENE3D,
        terrainProvider: Cesium.createWorldTerrain(),
        vrButton: false,
        animation: false,
        baseLayerPicker: false,
        geocoder: false,
        timeline: false,
        fullscreenButton: false,
        homeButton: false,
        // creditContainer: document.createElement("div"),
        infoBox: false,
        navigationHelpButton: false,
        sceneModePicker: false,
        scene3DOnly: false,
        shouldAnimate: true, //开启动画
        selectionIndicator: false,
      }));
      viewer.scene.globe.depthTestAgainstTerrain = true;
      viewer.cesiumWidget.creditContainer.style.display = "none";
      viewer.scene.screenSpaceCameraController.maximumZoomDistance = 600000;

      //   this.viewer = viewer;
      this.gohome(3);
      this.addYanmo(viewer);
      this.addbaselayers(viewer);
      //   添加掩膜
    },
    updateMap() {
      Bus.$emit("initlayers", true);
      let viewer = this.viewer;
      this.addAllLine(this.initlayers);
      this.addAllPoint();
      this.addAllLabel();
      this.addMouseclickandhover();
      this.addxzqhlayer();
      this.addmodel();
    },

    addmodel() {
      // this.viewer.scene.primitives.add(
      //   new Cesium.Cesium3DTileset({
      //     url: "http://60.165.108.42:9004/LT3DTILES/neiguan/tileset.json",
      //   })
      // );
      var translation = Cesium.Cartesian3.fromArray([0, 0, -50]);
      var m = Cesium.Matrix4.fromTranslation(translation);
      var tileset = this.viewer.scene.primitives.add(
        new Cesium.Cesium3DTileset({
          url: "http://60.165.108.42:9004/LT3DTILES/neiguan/tileset.json", //数据路径
          // maximumScreenSpaceError: 2, //最大的屏幕空间误差
          // maximumNumberOfLoadedTiles: 1000, //最大加载瓦片个数
          modelMatrix: m, //形状矩阵
        })
      );

      //生效
      // tileset._modelMatrix = m;
    },
    // 分组处理管线和阀门的数据
    async getData(callback) {
      // console.log(this.Thematiclayer, "Thematiclayer22222222222");
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" || element.type == "point") {
          element.data = [];
          element.load = false;
        }
      });
      const res = await getpolyLineData();
      // const res = line;
      // console.log("================1===========");
      if (res) {
        if (res.features.length == res.totalFeatures) {
          // this.addpolylineColume(viewer, res);
          // this.$store.commit("changeguanxiandata", res);
          this.guanxian.push(res.features);
          res.features.forEach((element) => {
            this.Thematiclayer.forEach((e) => {
              if (e.grade == element.properties.grade) {
                e.data.push(element);
              }
            });
          });
          //
        }
      }
      // console.log(this.Thematiclayer);

      const res1 = await getpolyPointData();
      // console.log(res1, "================2===========");
      if (res1) {
        if (res1.features.length == res1.totalFeatures) {
          // this.addbillboardCollection(viewer, res1);

          let data = {
            features: [],
          };

          res1.features.forEach((element) => {
            if (
              element.properties.sttp != "" &&
              element.properties.device_id != ""
            ) {
              data.features.push(element);
            }
          });
          // console.log(arr1, arr2, "数据")
          this.$store.commit("changefamendata", data);
          // let param=true
          // this.addAllPointEntity(data.features, function () {
          //   // alert("这是回调" + arg1 + " " + arg2);
          //   Bus.$emit("initlayers", true);
          // });

          // this.addAllPointEntity(data.features , function (params))

          data.features.forEach((element) => {
            this.Thematiclayer.forEach((e) => {
              if (e.sttp == element.properties.sttp) {
                e.data.push(element);
              }
            });
          });
        }
      }
      // console.log(this.Thematiclayer, "Thematiclayer");
      const res3 = await getpolyxzqhData();
      // console.log(res3, "================3===========");
      this.$store.commit("changexzqhlayerdata", res3.features);

      console.log(this.Thematiclayer, "Thematiclayer_3d数据获取");
      // debugger;
      // window.sessionStorage.setItem("token", "/cesium2d");
      callback();
    },
    addAllLine(callback) {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" && element.show == true) {
          this.addOnceLineEntity(element);
        }
      });
      callback();
    },
    addAllPoint() {
      var dataSource1 = new Cesium.CustomDataSource("dataSource1");
      let that = this;
      this.Thematiclayer.forEach((element) => {
        if (element.type == "point") {
          var showrgb;
          if (element.show == true) {
            showrgb = true;
          } else {
            showrgb = false;
          }
          // console.log(element);
          element.data.forEach((e) => {
            // console.log("deviceId", e.id);
            let imgtype = e.properties.sttp;
            var img;
            switch (imgtype) {
              case "0":
                // 管道分界监控点
                img = require("@/assets/poi/fjjcd.png");
                break;
              case "1":
                // 管道非分界监控点
                img = require("@/assets/poi/ffjjcd.png");
                break;
              case "2":
                // 蓄水池测控点
                img = require("@/assets/poi/xscjcd.png");
                break;
              case "3":
                // 泵站测控点
                img = require("@/assets/poi/bzjcd.png");
                break;
              case "4":
                img = require("@/assets/poi/sc.png");
                break;
              case "5":
                img = require("@/assets/poi/sfz.png");
                break;
            }
            let idData = {
              deviceId: e.properties.device_id,
              // jctype: e.properties.type,
              // sttp: e.properties.sttp,
            };
            dataSource1.entities.add(
              new Cesium.Entity({
                id: JSON.stringify(idData),
                position: Cesium.Cartesian3.fromDegrees(
                  e.geometry.coordinates[0],
                  e.geometry.coordinates[1],
                  4
                ),
                show: showrgb,
                billboard: {
                  pixelOffset: new Cesium.Cartesian2(0, -19),
                  image: img,
                  width: 34,
                  height: 38,
                  heightReference: Cesium.HeightReference.CLAMP_TO_GROUND,
                  disableDepthTestDistance: 2000000,
                },
              })
            );
          });
        }
      });
      dataSource1.id = "dataSource1";
      var dataSourcePromise = this.viewer.dataSources.add(dataSource1);
      dataSourcePromise.then(function (dataSource) {
        // console.log(dataSource,"dataSource")
        const pixelRange = 50;
        const minimumClusterSize = 2;
        const enabled = true;

        dataSource.clustering.enabled = enabled; //聚合开启
        dataSource.clustering.pixelRange = pixelRange; //设置像素范围，以扩展显示边框
        dataSource.clustering.minimumClusterSize = minimumClusterSize; //设置最小的聚合点数目，超过此数目才能聚合

        let removeListener;
        function combineIconAndLabel(url, label, size) {
          // 创建画布对象
          let canvas = document.createElement("canvas");
          canvas.width = size;
          canvas.height = size;
          let ctx = canvas.getContext("2d");

          let promise = new Cesium.Resource.fetchImage(url).then((image) => {
            // 异常判断
            try {
              ctx.drawImage(image, 0, 0);
            } catch (e) {
              // console.log(e);
            }

            // 渲染字体
            // font属性设置顺序：font-style, font-variant, font-weight, font-size, line-height, font-family
            ctx.fillStyle = Cesium.Color.WHITE.toCssColorString();
            ctx.font = "bold 18px Microsoft YaHei";
            ctx.textAlign = "center";
            ctx.textBaseline = "middle";
            ctx.fillText(label, size / 2, size / 2);

            return canvas;
          });
          return promise;
        }

        customStyle();

        function customStyle() {
          if (Cesium.defined(removeListener)) {
            removeListener();
            removeListener = undefined;
          } else {
            removeListener =
              dataSource.clustering.clusterEvent.addEventListener(function (
                clusteredEntities,
                cluster
              ) {
                cluster.label.show = false;
                cluster.billboard.show = true;
                cluster.billboard.id = cluster.label.id;
                cluster.billboard.verticalOrigin = Cesium.VerticalOrigin.BOTTOM;
                cluster.billboard.heightReference =
                  Cesium.HeightReference.CLAMP_TO_GROUND;

                if (clusteredEntities.length >= 40) {
                  // cluster.billboard.image = combineIconAndLabel(require('@/assets/poi/gz.png'), clusteredEntities.length, 255);
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/red.png",
                    clusteredEntities.length,
                    48
                  );

                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else if (clusteredEntities.length >= 30) {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/red.png",
                    clusteredEntities.length,
                    48
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else if (clusteredEntities.length >= 20) {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/orange.png",
                    clusteredEntities.length,
                    36
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else if (clusteredEntities.length >= 10) {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/green.png",
                    clusteredEntities.length,
                    32
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                } else {
                  cluster.billboard.image = combineIconAndLabel(
                    "https://a.amap.com/jsapi_demos/static/images/blue.png",
                    clusteredEntities.length,
                    32
                  );
                  cluster.billboard.width = 35;
                  cluster.billboard.height = 35;
                }
              });
          }
        }
      });
    },
    addAllLabel() {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" && element.show == true) {
          this.addOnceLabelEntity(element);
        }
      });
    },
    initlayers() {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "entity" || element.type == "geoserver") {
          if (element.layername == "ANDINGQU:xzqhlayer") {
            element.show = true;
          } else {
            element.show = false;
          }
        }
      });
      // Bus.$emit("initlayers", false);
      // console.log("xian  加载完毕1111111111111111111")
    },
    // 添加掩膜
    addYanmo(viewer) {
      let response = andingqu;
      // console.log(andingqu, "andingqu");
      var maskspoint = Cesium.Cartesian3.fromDegreesArray(
        response.features[0].geometry.coordinates[0].flat()
      );
      const entity1 = new Cesium.Entity({
        id: 1,
        polygon: {
          clampToGround: true,
          hierarchy: {
            // 绘制的区域太大容易卡顿
            positions: [
              {
                x: 3197104.586923899,
                y: 0.5580000157243585,
                z: 5500477.1339386385,
              },
              {
                x: 3197104.586923899,
                y: 0.5580000157243585,
                z: -5500477.1339386385,
              },
              {
                x: -3197104.5869239476,
                y: 3.915323898915733,
                z: -5500477.1339386385,
              },
              {
                x: -3197104.5869239476,
                y: 3.915323898915733,
                z: 5500477.1339386385,
              },
              {
                x: 3197104.586923899,
                y: 0.5580000157243585,
                z: 5500477.1339386385,
              },
            ],
            // holes是图形内需要挖空的区域
            holes: [
              {
                positions: maskspoint,
              },
            ],
          },
          material: Cesium.Color.fromCssColorString("#0C1F34").withAlpha(0.8),
          // material: Cesium.Color.WHITE.withAlpha(1),
        },
      });
      viewer.entities.add(entity1);
      // viewer.entities.add({
      //   polygon: {
      //     // 获取指定属性（positions，holes（图形内需要挖空的区域））
      //     hierarchy: {
      //       //左下左上右上右下
      //       // 0,60,0,-60,180,-60,180,60,0,-60
      //       positions: [
      //         {
      //           x: 3197104.586923899,
      //           y: -0.5580000157243585,
      //           z: 5500477.1339386385,
      //         },
      //         {
      //           x: 3197104.586923899,
      //           y: -0.5580000157243585,
      //           z: -5500477.1339386385,
      //         },
      //         {
      //           x: -3197104.5869239476,
      //           y: -3.915323898915733,
      //           z: -5500477.1339386385,
      //         },
      //         {
      //           x: -3197104.5869239476,
      //           y: -3.915323898915733,
      //           z: 5500477.1339386385,
      //         },
      //         {
      //           x: 3197104.586923899,
      //           y: -0.5580000157243585,
      //           z: 5500477.1339386385,
      //         },
      //       ],
      //     },
      //     // 边框
      //     outline: false,
      //     // 边框颜色
      //     outlineColor: Cesium.Color.WHITE,
      //     // 边框尺寸
      //     outlineWidth: 2,
      //     // 填充的颜色，withAlpha透明度
      //     // material: Cesium.Color.BLUE.withAlpha(0.5),
      //     material: Cesium.Color.fromCssColorString("#0C1F34").withAlpha(0.8),
      //     // 是否被提供的材质填充
      //     fill: true,
      //     // 是否显示
      //     show: true,
      //     // 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
      //     zIndex: 10,
      //   },
      // });
      // viewer.entities.add({
      // 			polygon: {
      // 				// 获取指定属性（positions，holes（图形内需要挖空的区域））
      // 				hierarchy: {
      // 					//左下左上右上右下
      // 					// 0,60,0,-60,180,-60,180,60,0,-60
      // 					positions: [{
      // 						x: 3197104.586923899,
      // 						y: 0.5580000157243585,
      // 						z: 5500477.1339386385
      // 					}, {
      // 						x: 3197104.586923899,
      // 						y: 0.5580000157243585,
      // 						z: -5500477.1339386385
      // 					}, {
      // 						x: -3197104.5869239476,
      // 						y: 3.915323898915733,
      // 						z: -5500477.1339386385
      // 					}, {
      // 						x: -3197104.5869239476,
      // 						y: 3.915323898915733,
      // 						z: 5500477.1339386385
      // 					}, {
      // 						x: 3197104.586923899,
      // 						y: 0.5580000157243585,
      // 						z: 5500477.1339386385
      // 					}],
      // 				},
      // 				// 边框
      // 				outline: false,
      // 				// 边框颜色
      // 				outlineColor: Cesium.Color.RED,
      // 				// 边框尺寸
      // 				outlineWidth: 200,
      // 				// 填充的颜色，withAlpha透明度
      // 				material: Cesium.Color.BLUE.withAlpha(0.5),
      // 				// 是否被提供的材质填充
      // 				fill: true,
      // 				// 是否显示
      // 				show: true,
      // 				// 顺序,仅当`clampToGround`为true并且支持地形上的折线时才有效。
      // 				zIndex: 10
      // 			}
      // 		});
    },
    // 添加基础底图（矢量图，矢量标注）
    addbaselayers(viewer) {
      //在线天地图矢量地图服务(墨卡托投影)
      // let token = "1e2e780493e477fb45f55694cae76a5a";
      let token = TOKRN;
      // console.log(token, "token");
      var TDT_VEC_W =
        "http://t0.tianditu.com/vec_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=vec&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&" +
        `tk=${token}`;
      var TDT_CVA_W =
        "http://t0.tianditu.com/cva_w/wmts?service=wmts&request=GetTile&version=1.0.0&LAYER=cva&tileMatrixSet=w&TileMatrix={TileMatrix}&TileRow={TileRow}&TileCol={TileCol}&style=default&format=tiles&" +
        `tk=${token}`;
      // console.log("1111111111")
      addLayer(viewer, "WMTS", "矢量图层", "ANDINGQU:sltclayer", TDT_VEC_W, {
        hue: 3,
        contrast: -1.2,
        show: false,
      });
      addLayer(viewer, "WMTS", "矢量文字标注", "tdtBasicLayer2", TDT_CVA_W);

      // console.log("222222222")

      // var baselayer = viewer.imageryLayers.addImageryProvider(
      //   new Cesium.WebMapTileServiceImageryProvider({
      //     url: TDT_VEC_W,
      //     layer: "ANDINGQU:sltclayer",
      //     style: "default",
      //     format: "image/jpeg",
      //     tileMatrixSetID: "GoogleMapsCompatible",
      //   })
      // );
      // viewer.imageryLayers.addImageryProvider(
      //   new Cesium.WebMapTileServiceImageryProvider({
      //     //调用影响中文注记服务

      //     url: TDT_CVA_W,
      //     layer: "tdtBasicLayer2",
      //     style: "default",
      //     format: "image/jpeg",
      //     tileMatrixSetID: "GoogleMapsCompatible",
      //   })
      // );
      // this.baselayer = baselayer;

      // 更改地图样式   色调    对比度
      // layerOption
      // baselayer.hue = 3;
      // baselayer.contrast = -1.2;
      // baselayer.show = false;
      // baselayer.id = "sltclayer";

      // console.log(viewer.imageryLayers._layers);
      // this.addlayers(viewer);
    },
    // 控制列表的显隐
    addImagelayer(data, type) {
      switch (type) {
        case true:
          this.Thematiclayer.forEach((element) => {
            if (element.layername == data.layername) {
              // console.log(element.layername, "true");
              this.addImagelayerEntity(element);
            }
          });

          break;
        case false:
          this.Thematiclayer.forEach((element) => {
            if (element.layername == data.layername) {
              // console.log(element.layername, "false")
              this.removeImagelayerEntity(element);
            }
          });

          break;

        default:
          break;
      }
    },
    // 控制管线与阀门的显隐
    addImagelayerEntity(res) {
      // console.log(res)
      switch (res.type) {
        case "line":
          this.addLineEntity(res);
          this.addLabelEntity(res);
          this.showLayerliuxiang(res);
          break;
        case "point":
          this.addPointEntity(res.data);
          break;
        case "entity":
          this.addentity(res.layername);
          break;
        case "geoserver":
          this.addgeoserver(res.layername);
          break;
        default:
          break;
      }
    },

    removeImagelayerEntity(res) {
      // console.log(res)
      switch (res.type) {
        case "line":
          this.removeLineEntity(res);
          this.removeLabelEntity(res);
          this.hideLayerliuxiang(res);
          break;
        case "point":
          this.removePointEntity(res.data);
          break;
        case "entity":
          this.removeentity(res.layername);
          break;
        case "geoserver":
          this.removegeoserver(res.layername);
          break;
        default:
          break;
      }
    },
    addLineEntity(res) {
      if (res.load) {
        this.addTwiceLineEntity(res);
      } else {
        this.addOnceLineEntity(res);
      }
    },
    addOnceLineEntity(res) {
      // console.log(res);
      // console.log("第一次加载");
      var instances = [];
      this.Thematiclayer.forEach((element) => {
        if (element.id == res.id) {
          element.load = true;
          var showrgb = 255;
          // if (element.show == true) {
          //   showrgb = 255;
          // } else {
          //   showrgb = 0;
          // }
          // console.log(element);
          element.data.forEach((e) => {
            if (e.geometry.coordinates[0][0].length == 3) {
              e.geometry.coordinates[0].forEach((item) => {
                // element.push( Math.round(Math.random()*100+1500));
                // item.push(0.1);
                item.pop();
              });
            }
            // console.log(e.geometry.coordinates[0].flat());
            let colortype = e.properties.grade;
            var color;
            switch (colortype) {
              case "0":
                // 输水干管
                // color = "#00a9fd";
                color = [255, 122, 0];

                break;
              case "1":
                // 供水干管
                // color = "#6fe1f9";
                color = [0, 169, 253];

                break;
              case "2":
                // 分支管
                // color = "#ff7a00";
                color = [111, 225, 249];

                break;
              case "3":
                // 直分支管
                // color = "#fda75d";
                color = [111, 225, 249];

                break;
              case "4":
                // 支管
                // color = "#44ab4f";
                color = [68, 171, 79];

                break;
              case "5":
                // 分支管
                // color = "#80b4eb";
                color = [128, 180, 235];

                break;
            }
            let idData = {
              UserID: e.properties.UserID,
            };
            let pos = e.geometry.coordinates[0].flat();
            instances.push(
              new Cesium.GeometryInstance({
                geometry: new Cesium.GroundPolylineGeometry({
                  positions: Cesium.Cartesian3.fromDegreesArray(pos),
                  width: 4,
                  // width: 10
                }),

                id: JSON.stringify(idData),
                attributes: {
                  color: Cesium.ColorGeometryInstanceAttribute.fromColor(
                    new Cesium.Color.fromBytes(
                      color[0],
                      color[1],
                      color[2],
                      showrgb
                    )
                  ),
                },
              })
            );
          });
        }
      });
      var primitive = new Cesium.GroundPolylinePrimitive({
        geometryInstances: instances,
        appearance: new Cesium.PolylineColorAppearance(),
      });

      // this.viewer.scene.groundPrimitives.add(primitive);

      // this.primitiveList.push(primitive);
      var lines = this.viewer.scene.groundPrimitives.add(primitive);
      lines.id = res.id;
      lines.zIndex = 0;

      //  console.log( this.viewer.scene.primitives)
      // console.log( this.viewer.scene)
      //  console.log( this.viewer.scene.groundPrimitives)

      this.primitiveList.push(primitive);
    },
    addTwiceLineEntity(res) {
      // console.log(this.viewer.scene.groundPrimitives)

      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("id") && res.id == element.id) {
          element.show = true;
        }
      });
    },
    removeLineEntity(res) {
      // console.log(this.primitiveList);
      // console.log(data, "====================");

      // console.log(this.viewer.scene.groundPrimitives)

      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("id") && res.id == element.id) {
          element.show = false;
        }
      });
    },
    addPointEntity(data) {
      // this.viewer.scene.requestRender();
      // console.log(this.viewer.dataSources);
      let datalist;
      this.viewer.dataSources._dataSources.forEach((element) => {
        if (element.id == "dataSource1") {
          // console.log(element)
          datalist = element._entityCollection._entities._array;
        }
      });

      data.forEach((element) => {
        let idData = {
          deviceId: element.properties.device_id,
        };
        datalist.forEach((e) => {
          if (JSON.stringify(idData) == e.id) {
            e.show = true;
          }
        });
      });
    },
    // 选择管点图层隐藏
    removePointEntity(data) {
      let datalist;
      this.viewer.dataSources._dataSources.forEach((element) => {
        if (element.id == "dataSource1") {
          // console.log(element)
          datalist = element._entityCollection._entities._array;
        }
      });
      // console.log(data, this.billboardCollection._billboards)
      data.forEach((element) => {
        let idData = {
          deviceId: element.properties.device_id,
        };
        datalist.forEach((e) => {
          if (JSON.stringify(idData) == e.id) {
            e.show = false;
          }
        });
      });
    },
    addLabelEntity(res) {
      // console.log(res);
      if (res.load1) {
        this.addTwiceLabelEntity(res);
      } else {
        this.addOnceLabelEntity(res);
      }
    },
    addOnceLabelEntity(res) {
      var labels = this.viewer.scene.primitives.add(
        new Cesium.LabelCollection()
      );
      labels.id = res.id;
      this.Thematiclayer.forEach((element) => {
        if (element.id == res.id) {
          element.load1 = true;
        }
      });

      // console.log(res);
      // console.log("第一次加载Label");
      var showrgb = true;
      res.data.forEach((e) => {
        var x = e.properties.X;
        var y = e.properties.Y;
        var z = e.properties.Z;

        let colortype = e.properties.grade;
        var color;
        switch (colortype) {
          case "0":
            // 输水干管
            // color = "#00a9fd";
            color = [255, 122, 0];

            break;
          case "1":
            // 供水干管
            // color = "#6fe1f9";
            color = [0, 169, 253];

            break;
          case "2":
            // 分支管
            // color = "#ff7a00";
            color = [111, 225, 249];

            break;
          case "3":
            // 直分支管
            // color = "#fda75d";
            color = [111, 225, 249];

            break;
          case "4":
            // 支管
            // color = "#44ab4f";
            color = [68, 171, 79];

            break;
          case "5":
            // 分支管
            // color = "#80b4eb";
            color = [128, 180, 235];

            break;
        }
        let idData = e.properties.name;

        // let pos = e.geometry.coordinates[0].flat();

        labels.add({
          id: e.id,
          show: showrgb,
          position: Cesium.Cartesian3.fromDegrees(x, y, z),
          text: idData,
          fillColor: new Cesium.Color.fromBytes(255, 255, 255, 255),
          showBackground: true,
          backgroundColor: new Cesium.Color.fromBytes(
            color[0],
            color[1],
            color[2],
            255
          ),
          font: "12px Helvetica",
          horizontalOrigin: Cesium.HorizontalOrigin.CENTER,
          verticalOrigin: Cesium.VerticalOrigin.CENTER,
          scale: 1.0,
          distanceDisplayCondition: new Cesium.DistanceDisplayCondition(
            0,
            3000
          ),
          // eyeOffset: Cesium.Cartesian3(200.0, 200.0, 0.0),
          // heightReference: Cesium.HeightReference.RELATIVE_TO_GROUND,
        });
      });
      // console.log(this.viewer.scene.primitives);
    },
    addTwiceLabelEntity(res) {
      // console.log(res);
      // console.log("第二次加载Label");
      this.viewer.scene.primitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("blendOption") && res.id == element.id) {
          element.show = true;
        }
      });
    },

    removeLabelEntity(res) {
      this.viewer.scene.primitives._primitives.forEach((element) => {
        if (element.hasOwnProperty("blendOption") && res.id == element.id) {
          element.show = false;
        }
      });
    },
    addentity(layername) {
      let that = this;
      // console.log(layername, "layername");
      switch (layername) {
        case "ANDINGQU:gxlxlayer":
          if (that.addgxlx == false) {
            this.addAllLiuxiang();
            that.addgxlx = true;
          } else {
            that.showAllLiuxiang();
          }

          break;
        case "ANDINGQU:xzqhlayer":
          for (let index = 0; index < that.xzqhlayerdata.length; index++) {
            // console.log(data[0][i])
            var entity = that.viewer.entities.getById("xzqhlayers" + index);
            // console.log(entity)
            entity.show = true;
          }
          break;

        default:
          break;
      }
    },

    removeentity(layername) {
      let that = this;
      switch (layername) {
        case "ANDINGQU:gxlxlayer":
          that.removeGuanlineliux();
          break;
        case "ANDINGQU:xzqhlayer":
          for (let index = 0; index < that.xzqhlayerdata.length; index++) {
            // console.log(data[0][i])
            var entity = that.viewer.entities.getById("xzqhlayers" + index);
            // console.log(entity)
            entity.show = false;
          }
          break;

        default:
          break;
      }
    },

    // addcunming: false,
    //   addcundian: false,
    //   addsltclayer: false,
    // 添加geoserver发布的图层（村名，村点位，行政区划）
    addgeoserver(layername) {
      let url = basegeoserver + "/geoserver/ANDINGQU/wms";
      let that = this;
      switch (layername) {
        case "ANDINGQU:wzbzlayer":
          if (!this.addcunming) {
            // addWMSLayer(that.viewer, "ANDINGQU:村名");
            addLayer(this.viewer, "WMS", "村名图层", "ANDINGQU:村名", url);
            this.addcunming = true;
          }

          // showOrhideWMSLayer(that.viewer, "ANDINGQU:村名", true);
          showLayer(that.viewer, "ANDINGQU:村名");
          break;
        case "ANDINGQU:dwbzlayer":
          if (!this.addcundian) {
            // addWMSLayer(that.viewer, "ANDINGQU:xzc");
            addLayer(this.viewer, "WMS", "村点位图层", "ANDINGQU:xzc", url);
            this.addcundian = true;
          }
          showLayer(that.viewer, "ANDINGQU:xzc");
          // showOrhideWMSLayer(that.viewer, "ANDINGQU:xzc", true);

          break;
        case "ANDINGQU:sltclayer":
          // showOrhideBaseLayer(that.viewer, "ANDINGQU:sltclayer", true);
          showLayer(that.viewer, "ANDINGQU:sltclayer");
          break;

        default:
          break;
      }
    },
    // 隐藏geoserver发布的图层（村名，村点位，行政区划）
    removegeoserver(layername) {
      let that = this;
      switch (layername) {
        case "ANDINGQU:wzbzlayer":
          // showOrhideWMSLayer(that.viewer, "ANDINGQU:村名", false);
          hideLayer(that.viewer, "ANDINGQU:村名");
          break;
        case "ANDINGQU:dwbzlayer":
          // showOrhideWMSLayer(that.viewer, "ANDINGQU:xzc", false);
          hideLayer(that.viewer, "ANDINGQU:xzc");
          break;
        case "ANDINGQU:sltclayer":
          // showOrhideBaseLayer(this.viewer, "ANDINGQU:sltclayer", false);
          hideLayer(that.viewer, "ANDINGQU:sltclayer");
          break;

        default:
          break;
      }
    },
    // 区域流向
    addAllLiuxiang() {
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line") {
          this.addOnceLayerLiuxiang(element);
        }
      });
      // this.labelslist.push(labels) ;
    },
    showLayerliuxiang(res) {
      if (!this.Thematiclayer[12].show) {
        return;
      }

      // console.log(res, "显示" + res.label + "流向");
      // console.log(this.Thematiclayer[12].show);
      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        // console.log(element);
        if (
          element.hasOwnProperty("id") &&
          String(element.id).substring(10) == res.label
        ) {
          element.show = true;
          this.viewer.scene.groundPrimitives.raiseToTop(element);
          // this.viewer.scene.groundPrimitives._primitives.splice(index, 1);
        }
      });
    },
    hideLayerliuxiang(res) {
      if (!this.Thematiclayer[12].show) {
        return;
      }
      // console.log(res, "隐藏" + res.label + "流向");
      // console.log(this.Thematiclayer[12].show);
      this.viewer.scene.groundPrimitives._primitives.forEach((element) => {
        // console.log(element);
        if (
          element.hasOwnProperty("id") &&
          String(element.id).substring(10) == res.label
        ) {
          element.show = false;
          this.viewer.scene.groundPrimitives.raiseToTop(element);
          // this.viewer.scene.groundPrimitives._primitives.splice(index, 1);
        }
      });
    },
    addOnceLayerLiuxiang(res) {
      var guanxiandata = res.data;

      var instances = [];
      guanxiandata.forEach((e, index) => {
        let pos = e.geometry.coordinates[0].flat();
        instances.push(
          new Cesium.GeometryInstance({
            geometry: new Cesium.GroundPolylineGeometry({
              positions: Cesium.Cartesian3.fromDegreesArray(pos),
              // width: element.properties.lineWidth / 5
              width: 2,
            }),
          })
        );
      });
      let material1 = new Cesium.Material({
        fabric: {
          uniforms: {
            uTime: 2,
            length1: 1000,
            alpha: 0.7,
          },
          source: `
  czm_material czm_getMaterial(czm_materialInput materialInput)
  {
    // 生成默认的基础材质
    czm_material material = czm_getDefaultMaterial(materialInput);
    // material.diffuse = vec3(0.8470588235294118, 0.66666666, 0.8156862745098039);
    // 发光
    material.specular = 1.0;
    material.shininess = 0.8;
    // material.emission = vec3(0.0, 0.66666666, 0.0);
    material.alpha = alpha;
    // material.diffuse = vec3(materialInput.st+uTime, 0.5);
    float strength = mod((materialInput.s+uTime) * length1, 1.0);
    material.diffuse = vec3(0.0, strength,1.0);
    return material;
  }
`,
        },
      });

      // 使用gasp实现补间动画，完成动画效果
      gsap.to(material1.uniforms, {
        uTime: 1,
        duration: 1000,
        repeat: -1,
        ease: "linear",
      });
      var primitive = new Cesium.GroundPolylinePrimitive({
        geometryInstances: instances,
        appearance: new Cesium.EllipsoidSurfaceAppearance({
          material: material1,
        }),
      });

      // this.viewer.scene.groundPrimitives.add(primitive);
      var lines = this.viewer.scene.groundPrimitives.add(primitive);
      lines.id = "gxliuxiang" + res.label;
      lines.show = res.show;
      this.primitiveList.push(primitive);
    },

    showAllLiuxiang() {
      console.log(" 显示所有流向");
      this.viewer.scene.groundPrimitives._primitives.forEach((e) => {
        // console.log(e);
        for (let index = 0; index < this.Thematiclayer.length; index++) {
          // const element = array[index];
          if (
            this.Thematiclayer[index].label == String(e.id).substring(10) &&
            this.Thematiclayer[index].show == true
          ) {
            e.show = true;
          }
        }
      });
    },

    removeGuanlineliux() {
      // console.log(
      //   this.viewer.scene.groundPrimitives._primitives,
      //   "this.viewer.scene.groundPrimitives._primitives"
      // );
      this.viewer.scene.groundPrimitives._primitives.forEach(
        (element, index) => {
          if (
            element.hasOwnProperty("id") &&
            String(element.id).slice(0, 10) == "gxliuxiang"
          ) {
            element.show = false;
            // this.viewer.scene.groundPrimitives._primitives.splice(index, 1);
          }
        }
      );
    },

    // showOrhideguanlineliux(type) {
    //   let that = this;
    //   switch (type) {
    //     case true:
    //       if (!this.guanlineliuxadd) {
    //         that.guanlineliux();
    //       }
    //       for (
    //         let index = 0;
    //         index < this.guanxiandata.features.length;
    //         index++
    //       ) {
    //         var entity = that.viewer.entities.getById("gxlxlayer" + index);
    //         entity.show = true;
    //         // that.viewer.entities.remove(entity);
    //       }
    //       break;
    //     case false:
    //       for (
    //         let index = 0;
    //         index < this.guanxiandata.features.length;
    //         index++
    //       ) {
    //         var entity = that.viewer.entities.getById("gxlxlayer" + index);
    //         entity.show = false;
    //         // that.viewer.entities.remove(entity);
    //       }
    //       break;

    //     default:
    //       break;
    //   }
    // },
    // 乡镇边界

    addxzqhlayer() {
      console.log(this.viewer.imageryLayers);
      // console.log(this.xzqhlayerdata, "xzqhlayerdata");
      for (let i = 0; i < this.xzqhlayerdata.length; i++) {
        // console.log(data[0][i])
        this.viewer.entities.add({
          id: "xzqhlayers" + i,
          // polygon: {
          //   // 绘制动态面实体时，面的位置信息必须是使用 Cesium.CallbackProperty() 和 Cesium.PolygonHierarchy() 返回的坐标
          //   // hierarchy: new Cesium.CallbackProperty(function() {
          //   //   return new Cesium.PolygonHierarchy(positions.concat(movePosition));
          //   // }, false),
          //   hierarchy: Cesium.Cartesian3.fromDegreesArray(data[0][i].geometry.coordinates[0][0].flat()),
          //   // material: Cesium.Color.fromRandom({ alpha: 0.2 }),
          //   material: Cesium.Color.fromCssColorString("rgba(201, 233, 255, 0.2)")
          // },
          // show:false,
          polyline: {
            positions: Cesium.Cartesian3.fromDegreesArray(
              this.xzqhlayerdata[i].geometry.coordinates[0][0].flat()
            ),
            // clampToGround: true,//开启贴地
            // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
            width: 4,
            clampToGround: true, //开启贴地
            // material: Cesium.Color.fromCssColorString("#04DE51")
            material: new Cesium.PolylineOutlineMaterialProperty({
              color: Cesium.Color.WHITE,
              outlineWidth: 2,
              // outlineColor: Cesium.Color.BLUE,
              outlineColor: Cesium.Color.fromCssColorString(
                "rgba(201, 233, 255, 0.1)"
              ),
            }),
          },
        });
      }
    },
    // showOrhideguanlinexzqh(type) {
    //   // let data = []
    //   // this.Thematiclayer.forEach(e => {
    //   //   if (e.layername == "ANDINGQU:xzqhlayer") {
    //   //     data.push(e.data[0])
    //   //   }
    //   // });

    //   switch (type) {
    //     case true:
    //       for (let i = 0; i < this.xzqhlayerdata.length; i++) {
    //         // console.log(data[0][i])
    //         this.viewer.entities.add({
    //           id: "xzqhlayers" + i,
    //           // polygon: {
    //           //   // 绘制动态面实体时，面的位置信息必须是使用 Cesium.CallbackProperty() 和 Cesium.PolygonHierarchy() 返回的坐标
    //           //   // hierarchy: new Cesium.CallbackProperty(function() {
    //           //   //   return new Cesium.PolygonHierarchy(positions.concat(movePosition));
    //           //   // }, false),
    //           //   hierarchy: Cesium.Cartesian3.fromDegreesArray(data[0][i].geometry.coordinates[0][0].flat()),
    //           //   // material: Cesium.Color.fromRandom({ alpha: 0.2 }),
    //           //   material: Cesium.Color.fromCssColorString("rgba(201, 233, 255, 0.2)")
    //           // },

    //           polyline: {
    //             positions: Cesium.Cartesian3.fromDegreesArray(
    //               this.xzqhlayerdata[i].geometry.coordinates[0][0].flat()
    //             ),
    //             // clampToGround: true,//开启贴地
    //             // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
    //             width: 4,
    //             clampToGround: true, //开启贴地
    //             // material: Cesium.Color.fromCssColorString("#04DE51")
    //             material: new Cesium.PolylineOutlineMaterialProperty({
    //               color: Cesium.Color.WHITE,
    //               outlineWidth: 2,
    //               // outlineColor: Cesium.Color.BLUE,
    //               outlineColor: Cesium.Color.fromCssColorString(
    //                 "rgba(201, 233, 255, 0.1)"
    //               ),
    //             }),
    //           },
    //         });
    //       }

    //       break;
    //     case false:
    //       // console.log("false")
    //       for (let j = 0; j < this.xzqhlayerdata.length; j++) {
    //         var entity = this.viewer.entities.getById("xzqhlayers" + j);
    //         // console.log(entity)
    //         this.viewer.entities.remove(entity);
    //       }
    //       break;

    //     default:
    //       break;
    //   }
    // },
    // 添加文字标注-村名
    // showOrhidewzbzlayer(type) {
    //   showOrhideWMSLayer(this.viewer, "ANDINGQU:村名", type);
    // },
    // // 添加图标标注-村点
    // showOrhidedwbzlayer(type) {
    //   showOrhideWMSLayer(this.viewer, "ANDINGQU:xzc", type);
    // },

    zoomout(type) {
      let position = this.viewer.camera.position;
      let cameraHeight =
        this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
          position
        ).height;
      // 每次缩小 20 倍，参数可改
      let moveRate = cameraHeight / 20;
      this.viewer.camera.moveForward(moveRate);
    },
    // 缩小
    zoomin(type) {
      let position = this.viewer.camera.position;
      let cameraHeight =
        this.viewer.scene.globe.ellipsoid.cartesianToCartographic(
          position
        ).height;
      // 每次缩小 20 倍，参数可改
      let moveRate = cameraHeight / 20;
      this.viewer.camera.moveBackward(moveRate);
    },
    //  回到初始位置
    gohome(type) {
      // console.log("gohome", type);
      switch (type) {
        case 3:
          cameraFlyto(this.viewer, [104.63125445585818, 34.8, 100000]);
          break;
        case 2:
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(104.65, 35.64, 200000),
          });
          break;

        default:
          break;
      }
    },
    // 添加地图覆盖物点悬事件
    addMouseclickandhover() {
      let that = this;
      let viewer = this.viewer;
      this.siteInfoDom = document.getElementById("info_box");
      // 取消鼠标双击事件
      viewer.cesiumWidget.screenSpaceEventHandler.removeInputAction(
        Cesium.ScreenSpaceEventType.LEFT_DOUBLE_CLICK
      );
      const handler = new Cesium.ScreenSpaceEventHandler(viewer.scene.canvas);
      handler.setInputAction(async function (click) {
        const pickedFeature = viewer.scene.pick(click.position);

        if (Cesium.defined(pickedFeature)) {
          // console.log(pickedFeature);
          // let parseid = JSON.parse(pickedFeature.id.id);
          // let id = pickedFeature.id.id;
          Bus.$emit("infowindowsIF", true);
          // console.log(pickedFeature, "pickedFeature");

          if (
            pickedFeature.hasOwnProperty("collection") &&
            pickedFeature.id.id.search("deviceId") >= 0
          ) {
            let parseid = JSON.parse(pickedFeature.id.id);
            // var id = pickedFeature.id.id;
            // console.log("阀门", parseid);
            // Bus.$emit("infodata", id);
            const res = await getBoxPointData(
              `device_id='${parseid.deviceId}'`
            );
            // console.log(res.features[0].properties.device_id, "图标点击之前")
            let idData = {
              deviceId: res.features[0].properties.device_id,
              sttp: res.features[0].properties.sttp,
              type: res.features[0].properties.TYPE,
              sp: res.features[0].properties.SP,
            };
            // that.infotype = "movement";
            let data = JSON.stringify(idData);
            Bus.$emit("infodata", data);
          } else if (
            typeof pickedFeature.id == "string" &&
            pickedFeature.id.search("UserID") >= 0
          ) {
            var id = pickedFeature.id;
            // console.log("管线", id);
            Bus.$emit("infodata", id);
            // ===================联通分析======================================================
            if (that.ltfx == true) {
              that.addlinesHeightColor(id);
              Bus.$emit("ltfxid", id);
            } else if (that.bgfx == true) {
              // ===================爆管分析======================================================
              that.addlinesHeightColor(id, true);
              Bus.$emit("bgfxid", id);
            } else if (that.zdmfx == true) {
              // ===================剖面分析======================================================
              that.addlinesHeightColor(id);
              Bus.$emit("zdmfxid", id);
            } else if (that.mapinit == true) {
              //设置工具栏弹框选项状态
              // that.addlinesHeightColor(id);
              that.colorheightone(id);
            }
          } else {
            // console.log("其他类型");
            Bus.$emit("dosetmethodes1", true);
          }
          // that.$store.commit("changemapstatus", true);
          // if (parseid.hasOwnProperty("UserID")) {
          //   // console.log("管线",pickedFeature.id.id)
          //   Bus.$emit("infodata", id);
          //   // ===================联通分析======================================================
          //   if (that.ltfx == true) {
          //     that.addlinesHeightColor(id);
          //     Bus.$emit("ltfxid", id);
          //   } else if (that.bgfx == true) {
          //     // ===================爆管分析======================================================
          //     that.addlinesHeightColor(id, true);
          //     Bus.$emit("bgfxid", id);
          //   } else if (that.zdmfx == true) {
          //     // ===================剖面分析======================================================
          //     that.addlinesHeightColor(id);
          //     Bus.$emit("zdmfxid", id);
          //   } else if (that.mapinit == true) {
          //     //设置工具栏弹框选项状态
          //     // that.addlinesHeightColor(id);

          //     that.colorheightone(id);
          //   }
          // } else if (parseid.hasOwnProperty("deviceId")) {
          // console.log("阀门",pickedFeature.id.id)
          // let ID = JSON.parse(pickedFeature.id.id);
          // const res = await getBoxPointData(
          //   `device_id='${parseid.deviceId}'`
          // );
          // // console.log(res.features[0].properties.device_id, "图标点击之前")
          // let idData = {
          //   deviceId: res.features[0].properties.device_id,
          //   sttp: res.features[0].properties.sttp,
          //   type: res.features[0].properties.TYPE,
          //   sp: res.features[0].properties.SP,
          // };
          // // that.infotype = "movement";
          // let data = JSON.stringify(idData);
          // Bus.$emit("infodata", data);
          // }
        } else {
        }
      }, Cesium.ScreenSpaceEventType.LEFT_CLICK);
    },

    // 高亮管线（id）
    addlinesHeightColor(id, type) {
      // console.log(id, "id");
      var that = this;
      this.Thematiclayer.forEach((element) => {
        if (element.type == "line" && element.show == true) {
          element.data.forEach((item) => {
            let idData = {
              UserID: item.properties.UserID,
            };
            if (JSON.stringify(idData) === id) {
              // console.log(id, "===================");
              that.addLinesInfoData(id, type);
              var attribute;
              if (type) {
                this.primitiveList.forEach((e) => {
                  attribute = e.getGeometryInstanceAttributes(id);
                  // console.log(attribute, e, "attribute");
                  if (attribute != undefined) {
                    attribute.color =
                      Cesium.ColorGeometryInstanceAttribute.toValue(
                        Cesium.Color.fromRandom({
                          alpha: 0.0,
                        })
                        // Cesium.Color.RED
                        // Cesium.Color.fromCssColorString(color)
                      );
                  }
                });
              } else {
                this.primitiveList.forEach((e) => {
                  attribute = e.getGeometryInstanceAttributes(id);
                  // console.log(attribute, "attribute");
                  if (attribute != undefined) {
                    attribute.color =
                      Cesium.ColorGeometryInstanceAttribute.toValue(
                        // Cesium.Color.fromRandom({
                        //   alpha: 1.0,
                        // })
                        Cesium.Color.BLUE
                        // Cesium.Color.fromCssColorString(color)
                      );
                  }
                });
              }
            } else {
              // console.log(id, "=====buxianshi==============");
            }
            // console.log(id)
          });
        }
      });
    },
    // 暂存高亮之后管线的信息（根据管线id）(方便清除)
    async addLinesInfoData(id, type) {
      // console.log(id)
      let ID = JSON.parse(id);
      const res = await getBoxLineData(`UserID='${ID.UserID}'`);
      // console.log(res, "res=============================");
      if (res.features[0] != []) {
        this.heightColorlinesList.push(res.features[0]);
        if (type) {
          this.addmaterialREDline();
        }
      }
    },
    addmaterialREDline() {
      var x = 1;
      var flog = true;
      var material = new Cesium.ColorMaterialProperty(
        new Cesium.CallbackProperty(function () {
          if (flog) {
            x = x - 0.05;
            if (x <= 0) {
              flog = false;
            }
          } else {
            x = x + 0.05;
            if (x >= 1) {
              flog = true;
            }
          }
          // console.log(x)
          return Cesium.Color.RED.withAlpha(x);
        }, false)
      );
      this.viewer.entities.add({
        name: "P",
        id: "materialREDline" + this.heightColorlinesList.length,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(
            this.heightColorlinesList[
              this.heightColorlinesList.length - 1
            ].geometry.coordinates[0].flat()
          ),
          clampToGround: true, //开启贴地
          // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
          width: 6,
          // material: Cesium.Color.RED, //颜色
          material: material,
        },
      });
    },
    removematerialREDline() {
      this.heightColorlinesList.forEach((element, index) => {
        var entity = this.viewer.entities.getById(
          "materialREDline" + (index + 1)
        );
        // console.log("materialREDline" + index);
        this.viewer.entities.remove(entity);
      });
    },
    // 清除屏幕上高亮的线的数据================================
    clearHeightColoridlist() {
      // console.log(this.heightColorlinesList, "this.heightColorlinesList");
      this.clearHeightColor(this.heightColorlinesList);
    },
    clearHeightColor(data) {
      // console.log(data);
      data.forEach((element) => {
        let colortype = element.properties.grade;
        var color;
        var img;
        switch (colortype) {
          case "0":
            // 输水干管
            // color = "#00a9fd";
            color = [255, 122, 0];
            img = "./images/0000.png";

            break;
          case "1":
            // 供水干管
            // color = "#6fe1f9";
            color = [0, 169, 253];
            img = "./images/1111.png";

            break;
          case "2":
            // 分支管
            // color = "#ff7a00";
            color = [111, 225, 249];
            img = "./images/2222.png";

            break;
          case "3":
            // 直分支管
            // color = "#fda75d";
            color = [111, 225, 249];
            img = "./images/2222.png";

            break;
          case "4":
            // 支管
            // color = "#44ab4f";
            color = [68, 171, 79];
            img = "./images/4444.png";

            break;
          case "5":
            // 分支管
            // color = "#80b4eb";
            color = [128, 180, 235];
            img = "./images/5555.png";

            break;

          default:
            color = "#ffffff";
            break;
        }
        let id = { UserID: element.properties.UserID };
        // var entity = this.viewer.entities.getById(JSON.stringify(id));
        // // console.log(entity,"entity")
        // // this.viewer.entities.remove(entity);
        // entity.polyline.material = new Cesium.Color.fromBytes(
        //   color[0],
        //   color[1],
        //   color[2],
        //   255
        // );
        // entity.polylineVolume.material.url = img;
        var attribute;
        this.primitiveList.forEach((e) => {
          attribute = e.getGeometryInstanceAttributes(JSON.stringify(id));
          // console.log(attribute, "attribute");
          if (attribute != undefined) {
            attribute.color = Cesium.ColorGeometryInstanceAttribute.toValue(
              // Cesium.Color.fromRandom({
              //   alpha: 1.0,
              // })
              // Cesium.Color.RED
              new Cesium.Color.fromBytes(color[0], color[1], color[2], 255)
            );
          }
        });
      });
    },
    // 添加红色标点
    addnewpoint(id) {
      let datalist =
        this.viewer.dataSources._dataSources[0]._entityCollection._entities
          ._array;

      datalist.forEach((e) => {
        if (id == e.id) {
          this.addPointInfoData(id, e.show);
          // alert("数据找到了");
          // console.log(e,'数据找到了')
          e.show = true;
          e._billboard.image = require("@/assets/poi/gz.png");
        } else {
          return;
          // alert('数据找bu到了')
        }
      });
    },
    // 暂存高亮之后图标的信息（根据图标id）(方便清除)
    async addPointInfoData(id, type) {
      // console.log(id)
      let ID = JSON.parse(id);
      const res = await getBoxPointData(`device_id='${ID.deviceId}'`);

      // console.log(res, "res===============device_id==============")
      this.heightColorpointsList = res.features[0];

      this.heightColorpointsType = type;
    },
    //  清除屏幕上所有高亮的标点
    removenewpoint() {
      // console.log(this.heightColorpointsList,"this.heightColorpointsList")
      this.clearpointHeightColor(
        this.heightColorpointsList,
        this.heightColorpointsType
      );
      this.heightColorpointsList = null;
      this.heightColorpointsType = null;
    },
    // 清除屏幕上高亮的标点(还原屏幕上的点位)
    clearpointHeightColor(data, type) {
      if (!data) {
        return;
      }
      let imgtype = data.properties.sttp;
      var img;
      switch (imgtype) {
        case "0":
          // 管道分界监控点
          img = require("@/assets/poi/fjjcd.png");
          break;
        case "1":
          // 管道非分界监控点
          img = require("@/assets/poi/ffjjcd.png");
          break;
        case "2":
          // 蓄水池测控点
          img = require("@/assets/poi/xscjcd.png");
          break;
        case "3":
          // 泵站测控点
          img = require("@/assets/poi/bzjcd.png");
          break;
        case "4":
          img = require("@/assets/poi/sc.png");
          break;
        case "5":
          img = require("@/assets/poi/sfz.png");
          break;
      }
      let idData = {
        deviceId: data.properties.device_id,
      };
      let datalist =
        this.viewer.dataSources._dataSources[0]._entityCollection._entities
          ._array;

      datalist.forEach((e) => {
        if (JSON.stringify(idData) == e.id) {
          // alert('数据找到了')
          // console.log(e,'数据找到了')
          e.show = type;
          e._billboard.image = img;
        } else {
          return;
          // alert('数据找bu到了')
        }
      });
    },
    // 定位
    dingweiFly(data) {
      // console.log(data,this.btntype,"----3----")
      switch (this.btntype) {
        case "3":
          // alert(3)
          // cameraFlyto(this.viewer, [data[0] + 0.006, data[1] - 0.015, 2000]);
          // cameraFlyto(this.viewer, [data[0], data[1], 2000]);
          // this.viewer.camera.flyTo({
          //   destination: Cesium.Cartesian3.fromDegrees(data[0], data[1], 3000),
          // });
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
              data[0],
              data[1],
              data[2] + 2000
            ),
            // orientation: {
            //   heading: Cesium.Math.toRadians(20.0),
            //   pitch: Cesium.Math.toRadians(-35.0),
            //   roll: 0.0,
            // },
          });
          break;
        case "2":
          // alert(2)
          this.viewer.camera.flyTo({
            destination: Cesium.Cartesian3.fromDegrees(
              data[0],
              data[1],
              data[2]
            ),
          });
          break;

        default:
          break;
      }
    },
    //  =====================================================测量================================================================================
    measurePolyLine(c, type) {
      let showlabel;
      if (type) {
        showlabel = false;
      } else {
        showlabel = true;
      }
      let measure = new Cesium.Measure(this.viewer);

      measure.drawLineMeasureGraphics({
        clampToGround: this.clampToGround,
        showlabel: showlabel,
        callback: (e) => {
          // console.log(e);
          if (showlabel == false) {
            this.getposition(e);
          }
        },
      });
    },
    measurePolygon(c, type) {
      let showlabel;
      if (type) {
        showlabel = false;
      } else {
        showlabel = true;
      }
      let measure = new Cesium.Measure(this.viewer);
      measure.drawAreaMeasureGraphics({
        clampToGround: this.clampToGround,
        showlabel: showlabel,
        callback: (e) => {
          e.splice(e.length - 2, 1);
          // this.pos=e
          // console.log(e);
          // pos = e;
          // console.log(pos, "pos");
          // return pos;
          if (showlabel == false) {
            this.getposition(e);
          }
        },
      });
    },
    measureHeight() {
      let measure = new Cesium.Measure(this.viewer);
      // 三维量测
      measure.drawTrianglesMeasureGraphics({ callback: () => {} });
    },
    measureDestroy() {
      let arr = this.viewer.dataSources._dataSources;

      for (let index = 0; index < arr.length; index++) {
        // const element = array[index];
        if (arr[index]._name != "dataSource1") {
          this.viewer.dataSources.remove(arr[index]);
        }
      }
    },
    getposition(data) {
      Bus.$emit("positions", data);
      // console.log(data, "data");
    },

    //  =====================================================缓冲区================================================================================

    // 查找并添加有区域缓冲的线的缓冲区域
    async colorheightone(id) {
      this.clearHeightColoridlist();
      this.addlinesHeightColor(id);
      this.removeallyxqu();
      this.selectallyxqu1([id]);
    },
      // 二次修改影响区域
      selectallyxqu1(idlist) {
      let that = this;
      const yxquList = [];

      function createRecord(id) {
        return getBoxLineData(`UserID='${id}'`);
      }
      const arrays = [];
      idlist.forEach((element) => {
        // console.log(element);
        arrays.push(createRecord(JSON.parse(element).UserID));
      });

      // 当所有请求都成功完成时，responses 是一个包含所有响应的数组
      Promise.all(arrays)
        .then((responses) => {
          // console.log(responses);

          responses.forEach((element) => {
            if (element.features[0].properties.yxquID.split("、").length > 0) {
              element.features[0].properties.yxquID.split("、").forEach((e) => {
                yxquList.push(e);
              });
            } else {
              yxquList.push(element.features[0].properties.yxquID);
            }
            // yxquList.push(element.features[0].properties.yxquID.split("、"));
          });
          function unique(arr) {
            return Array.from(new Set(arr));
          }
          // console.log(yxquList);
          // console.log(unique(yxquList));

          let datalist = unique(yxquList);
          datalist = datalist.filter((item) => item != "");
          that.selectyxqu(datalist);
        })
        .catch((error) => {
          // 如果任何一个请求失败，将会进入这个 catch 块
          console.log(error);
        });
    },
    selectyxqu(list) {
      let that = this;
      // console.log(list);
      function createRecord(id) {
        return getYXQYidData(`id='${id}'`);
      }
      const arrays = [];
      list.forEach((element) => {
        // console.log(element);

        arrays.push(createRecord(element));
      });

      // 当所有请求都成功完成时，responses 是一个包含所有响应的数组
      Promise.all(arrays)
        .then((responses) => {
          // console.log(responses);

          responses.forEach((element, i) => {
            if (element.features.length != 0) {
              that.addyxqy(element, i);
              this.allyxqudata.push(i);
            }
          });
        })
        .catch((error) => {
          // 如果任何一个请求失败，将会进入这个 catch 块
          console.log(error);
        });
    },
    addyxqy(res, id) {
      var x = 1;
      var flog = true;
      let material2 = new Cesium.ColorMaterialProperty(
        new Cesium.CallbackProperty(function () {
          if (flog) {
            x = x - 0.01;
            if (x <= 0) {
              flog = false;
            }
          } else {
            x = x + 0.01;
            if (x >= 1) {
              flog = true;
            }
          }
          // console.log(x)
          return Cesium.Color.YELLOW.withAlpha(x);
        }, false)
      );
      let line = {
        name: "P",
        id: "hcqy" + id,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(
            res.features[0].geometry.coordinates[0][0].flat()
          ),
          clampToGround: true, //开启贴地
          // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
          width: 2,
          // material: Cesium.Color.YELLOW, //颜色
          material: material2,
        },
        polygon: {
          hierarchy: Cesium.Cartesian3.fromDegreesArray(
            res.features[0].geometry.coordinates[0][0].flat()
          ),
          material: material2,
        },
      };
      this.viewer.entities.add(line);
    },
    //  查找添加所有的缓冲区
    async selectallyxqu(id, type) {
      let ID = JSON.parse(id);
      const res = await getBoxLineData(`UserID='${ID.UserID}'`);
      if (!res) {
        return;
      }
      // console.log(res);
      let yxquID = res.features[0].properties.yxquID;
      // console.log(yxquID);
      // console.log(yxquID.split("、"));
      var yxquIDlist = yxquID.split("、");

      yxquIDlist.forEach(async (element) => {
        // console.log(element)
        let id = element;
        const res1 = await getYXQYidData(`id='${id}'`);
        // console.log(res1, "rrrrrrrrrrrrrrrrrrrrrrrrrrrrrrr");
        if (!res1) {
          return;
        }
        if (res1.features.length != 0) {
          // console.log(res1, "=======");
          this.allyxqudata.push(id);
          this.addqycxpoly(res1, id, type);
        }
      });

      // console.log(id)
    },
    // 添加区域缓冲区
    addqycxpoly(res1, id, type) {
      var material1;
      var material2;

      if (type == true) {
        var x = 1;
        var flog = true;
        material1 = new Cesium.ColorMaterialProperty(
          new Cesium.CallbackProperty(function () {
            if (flog) {
              x = x - 0.01;
              if (x <= 0) {
                flog = false;
              }
            } else {
              x = x + 0.01;
              if (x >= 1) {
                flog = true;
              }
            }
            // console.log(x)
            return Cesium.Color.WHEAT.withAlpha(x);
          }, false)
        );
        material2 = new Cesium.ColorMaterialProperty(
          new Cesium.CallbackProperty(function () {
            if (flog) {
              x = x - 0.01;
              if (x <= 0) {
                flog = false;
              }
            } else {
              x = x + 0.01;
              if (x >= 1) {
                flog = true;
              }
            }
            // console.log(x)
            return Cesium.Color.YELLOW.withAlpha(x);
          }, false)
        );
      } else {
        material1 = Cesium.Color.WHEAT.withAlpha(0.2);
        material2 = Cesium.Color.YELLOW.withAlpha(1);
      }

      let line = this.viewer.entities.add({
        name: "P",
        id: "hcqy" + id,
        polyline: {
          positions: Cesium.Cartesian3.fromDegreesArray(
            res1.features[0].geometry.coordinates[0][0].flat()
          ),
          clampToGround: true, //开启贴地
          // positions: Cesium.Cartesian3.fromDegreesArrayHeights(element.geometry.coordinates[0].flat()),
          width: 2,
          // material: Cesium.Color.YELLOW, //颜色
          material: material2,
        },
        polygon: {
          clampToGround: true, //开启贴地
          hierarchy: Cesium.Cartesian3.fromDegreesArray(
            res1.features[0].geometry.coordinates[0][0].flat()
          ),
          // eslint-disable-next-line new-cap
          // material: Cesium.Color.WHEAT.withAlpha(0.2),
          // material: new Cesium.ColorMaterialProperty(new Cesium.CallbackProperty(function () {
          //   if (flog) {
          //     x = x - 0.01;
          //     if (x <= 0) {
          //       flog = false;
          //     }
          //   } else {
          //     x = x + 0.01;
          //     if (x >= 1) {
          //       flog = true;
          //     }
          //   }
          //   // console.log(x)
          //   return Cesium.Color.WHEAT.withAlpha(x);
          // }, false))

          material: material1,
        },
      });
    },
    // 删除缓冲区的区域
    removeallyxqu() {
      this.allyxqudata.forEach((element) => {
        var entity = this.viewer.entities.getById("hcqy" + element);
        this.viewer.entities.remove(entity);
      });
    },
    drawPolygon(positions) {
      // console.log(positions)
      // this.positions = positions;
      let viewer = this.viewer;
      if (positions.length < 2) return;
      return viewer.entities.add({
        name: "",
        id: "mianjhdx",
        polygon: {
          // hierarchy: positions,
          // // eslint-disable-next-line new-cap
          // material: new Cesium.ColorMaterialProperty(
          //   Cesium.Color.WHEAT.withAlpha(0.4)
          // ),
          clampToGround: true, //开启贴地
          hierarchy: new Cesium.PolygonHierarchy(positions),
          material: Cesium.Color.RED.withAlpha(0.3),
          classificationType: Cesium.ClassificationType.BOTH,
        },
      });
    },
    removePolygon() {
      var entity = this.viewer.entities.getById("mianjhdx");
      this.viewer.entities.remove(entity);
    },
    //  =====================================================开挖分析================================================================================
    excavationAnalysis(data, height) {
      var pos = [];
      data.forEach((element) => {
        pos.push([element.lng, element.lat]);
      });
      this.TerrainClipPlan.oldpos = pos;
      this.TerrainClipPlan.height = height;
      this.TerrainClipPlan.bottomImg = require("@/assets/map/bottomImg.jpg");
      this.TerrainClipPlan.wallImg = require("@/assets/map/wallImg.jpg");
      this.addheight(pos);
    },

    draw(position, depth, wallimg, bottomimg) {
      this.clippings(position);
      this.createWell(position, depth, bottomimg);
      this.createWellWall(this.newpos, depth, wallimg);
    },
    // 插值获取更详细坐标
    function1(arrl) {
      console.log(arrl);
      var positions = [];
      positions.push(arrl[0]);
      for (let index = 0; index < arrl.length - 1; index++) {
        var line = turf.lineString([arrl[index], arrl[index + 1]]);
        var from = turf.point(arrl[index]);
        var to = turf.point(arrl[index + 1]);
        var options = { units: "meters" };
        var distance = turf.distance(from, to, options);
        for (let i = 1; i < distance.toFixed(0) / 5; i++) {
          var stop = 5 * i;
          var sliced = turf.lineSliceAlong(line, 0, stop, {
            units: "meters",
          });
          positions.push(sliced.geometry.coordinates[1]);
        }
      }
      return positions;
    },
    createWell(position, depth, bottomimg) {
      var posArr = Array.from(position);
      posArr.forEach((element) => {
        element.push(this.minheight - depth);
      });
      // console.log(polygonOne);
      let polygon = new Cesium.PolygonGeometry({
        polygonHierarchy: new Cesium.PolygonHierarchy(
          Cesium.Cartesian3.fromDegreesArrayHeights(posArr.flat())
        ),
        perPositionHeight: true,
        closeBottom: false,
      });
      let geometry = Cesium.PolygonGeometry.createGeometry(polygon);

      var i = new Cesium.Material({
          fabric: {
            type: "Image",
            uniforms: {
              image: bottomimg,
            },
          },
        }),
        a = new Cesium.MaterialAppearance({
          translucent: !1,
          flat: !0,
          material: i,
        });
      this.bottomSurface = new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
          geometry: geometry,
        }),
        appearance: a,
        asynchronous: !1,
      });
      let bottomSurfaces = this.viewer.scene.primitives.add(this.bottomSurface);
      bottomSurfaces.id = "bottomWall";
    },
    addheight(position) {
      var posArr = Array.from(position);
      let pos = this.function1(posArr);
      var terrainProvider = Cesium.createWorldTerrain();
      var positions = [];
      pos.forEach((element) => {
        // console.log(element)
        positions.push(Cesium.Cartographic.fromDegrees(element[0], element[1]));
      });

      const promise = Cesium.sampleTerrainMostDetailed(
        terrainProvider,
        // Cesium.Cartesian3.fromDegreesArray(positions.flat())
        positions
      );
      // console.log(promise);

      promise.then((i) => {
        let newpos = [];
        i.forEach((element) => {
          var s = Cesium.Cartesian3.fromRadians(
            element.longitude,
            element.latitude,
            element.height
          );
          newpos.push(s);
        });
        console.log(newpos);
        this.newpos = newpos;
        this.getMinHeight(newpos);
      });
    },
    createWellWall(position, depth, wallimg) {
      let that = this;
      let maximumHeights = [];
      this.newpos.forEach((element) => {
        let cartorgraphic = Cesium.Cartographic.fromCartesian(element);
        // console.log(cartorgraphic.height)
        maximumHeights.push(cartorgraphic.height);
      });
      // 墙体最高为0
      // let maximumHeights = new Array(this.n.length).fill(5600);
      // 墙体最低为-1600
      let minimumHeights = new Array(this.newpos.length).fill(
        this.minheight - depth
      );

      let wall = new Cesium.WallGeometry({
        positions: that.newpos,
        maximumHeights: maximumHeights,
        minimumHeights: minimumHeights,
      });
      let geometry = Cesium.WallGeometry.createGeometry(wall);
      var a = new Cesium.Material({
          fabric: {
            type: "Image",
            uniforms: {
              image: require("@/assets/map/wallImg.jpg"),
            },
          },
        }),
        n = new Cesium.MaterialAppearance({
          translucent: !1,
          flat: !0,
          material: a,
        });
      this.wellWall = new Cesium.Primitive({
        geometryInstances: new Cesium.GeometryInstance({
          geometry: geometry,
          attributes: {
            color: Cesium.ColorGeometryInstanceAttribute.fromColor(
              Cesium.Color.GREY
            ),
          },
          // id: "PitWall",
        }),
        appearance: n,
        asynchronous: !1,
      });
      let PitWall = this.viewer.scene.primitives.add(this.wellWall);
      PitWall.id = "pitWall";
    },
    clippings(position) {
      console.log(position, "position");
      var posArr = Array.from(position);
      var booleanClockwisearr = turf.lineString(position);
      // console.log(turf.booleanClockwise(booleanClockwisearr))
      let booleanClockwise = turf.booleanClockwise(booleanClockwisearr);
      if (booleanClockwise) {
        posArr.reverse();
      }

      let that = this;
      let clippingPlanes1 = this.createClippingPlane(posArr);
      // let clippingPlanes2 = this.createClippingPlane(this.polygonTwo);
      this.viewer.scene.globe.clippingPlanes =
        new Cesium.ClippingPlaneCollection({
          planes: clippingPlanes1,
          edgeWidth: 1,
          edgeColor: Cesium.Color.WHITE,
          enabled: !0,
        });
      // let clippingPlaneCollection2 = new Cesium.ClippingPlaneCollection({
      //   planes: clippingPlanes2,
      //   edgeWidth: 1,
      //   edgeColor: Cesium.Color.WHITE,
      // });
      if (!that.isClipping) {
        that.viewer.scene.globe.depthTestAgainstTerrain = true;
        // that.viewer.scene.globe.multiClippingPlanes =
        //   new Cesium.MultiClippingPlaneCollection({
        //     collections: [clippingPlaneCollection1, clippingPlaneCollection2],
        //     edgeWidth: 1,
        //     edgeColor: Cesium.Color.WHITE,
        //   });
        that.isClipping = true;
      } else {
        // that.viewer.scene.globe.multiClippingPlanes = null;
        that.isClipping = false;
      }
    },
    /**
     * 根据多边形数组创建裁切面
     * @param points_ 多边形数组集合
     * @returns {[]} 返回裁切面数组
     */
    createClippingPlane(points_) {
      let points = [];
      for (let i = 0; i < points_.length - 1; i++) {
        points.push(
          Cesium.Cartesian3.fromDegrees(points_[i][0], points_[i][1])
        );
      }
      // console.log(points);
      this.points = points;
      let pointsLength = points.length;
      let clippingPlanes = []; // 存储ClippingPlane集合
      for (let i = 0; i < pointsLength; ++i) {
        let nextIndex = (i + 1) % pointsLength;
        let midpoint = Cesium.Cartesian3.add(
          points[i],
          points[nextIndex],
          new Cesium.Cartesian3()
        );
        midpoint = Cesium.Cartesian3.multiplyByScalar(midpoint, 0.5, midpoint);

        let up = Cesium.Cartesian3.normalize(midpoint, new Cesium.Cartesian3());
        let right = Cesium.Cartesian3.subtract(
          points[nextIndex],
          midpoint,
          new Cesium.Cartesian3()
        );
        right = Cesium.Cartesian3.normalize(right, right);

        let normal = Cesium.Cartesian3.cross(
          right,
          up,
          new Cesium.Cartesian3()
        );
        normal = Cesium.Cartesian3.normalize(normal, normal);

        let originCenteredPlane = new Cesium.Plane(normal, 0.0);
        let distance = Cesium.Plane.getPointDistance(
          originCenteredPlane,
          midpoint
        );

        clippingPlanes.push(new Cesium.ClippingPlane(normal, distance));
      }
      return clippingPlanes;
    },
    getMinHeight(posarr) {
      var posArr = Array.from(posarr);
      var minarrheight = [];
      posArr.forEach((element) => {
        // minarrheight.push(element.z);
        minarrheight.push(this.Cartesian3_to_WGS84(element).alt);
      });
      const min = Math.min(...minarrheight);
      this.minheight = min;
      this.draw(
        this.TerrainClipPlan.oldpos,
        this.TerrainClipPlan.height,
        this.TerrainClipPlan.wallImg,
        this.TerrainClipPlan.bottomImg
      );
    },
    Cartesian3_to_WGS84(point) {
      var cartesian3 = new Cesium.Cartesian3(point.x, point.y, point.z);
      var cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      var lat = Cesium.Math.toDegrees(cartographic.latitude);
      var lng = Cesium.Math.toDegrees(cartographic.longitude);
      var alt = cartographic.height;
      return {
        lat: lat,
        lng: lng,
        alt: alt,
      };
    },

    WGS84_to_Cartesian3(point) {
      var car33 = Cesium.Cartesian3.fromDegrees(
        point.lng,
        point.lat,
        point.alt
      );
      var x = car33.x;
      var y = car33.y;
      var z = car33.z;
      return {
        x: x,
        y: y,
        z: z,
      };
    },
    clearExcavation() {
      // this.viewer.scene.globe.depthTestAgainstTerrain = true;
      this.viewer.scene.globe.clippingPlanes = null;
      this.viewer.scene.primitives.remove(this.wellWall);
      this.viewer.scene.primitives.remove(this.bottomSurface);
      // if (!this.terrainClipPlan) {
      //   return;
      // }
      // this.terrainClipPlan.clear();
    },
    //  =====================================================漫游================================================================================
    startFly(datas) {
      let that = this;
      // console.log(datas, "data三维漫游数据");
      let newline = getlenLonlat(datas, 5);
      getHeigthByLonLat1(newline, this.initFly);
      // 根据经纬度获取高度
      function getHeigthByLonLat1(data, callback) {
        var positions = [];
        data.forEach((element) => {
          positions.push(
            Cesium.Cartographic.fromDegrees(element[0], element[1])
          );
        });
        var promise = new Cesium.sampleTerrain(
          that.viewer.terrainProvider,
          13,
          positions
        );
        promise.then((i) => {
          //  console.log("getheight", i);
          i.forEach((element, index) => {
            data[index].push(element.height);
          });
          callback(data);
        });
      }
      // var line = turf.lineString(datas);
      // var length = Math.floor(turf.length(line, { units: "meters" }) / 5);
      // // console.log(Math.floor(length));
      // let that = this;
      // let viewer = this.viewer;
      // // console.log(this.manyoudata, "this.manyoudata33333333333");
      // // let pos = this.manyoudata;
      // var pos = Object.assign([], datas);
      // var heightlist = [];
      // // pos.forEach((element) => {
      // //   getHeigthByLonLat(element[0], element[1], ceshi);
      // // });
      // getHeigthByLonLat1(pos, length, this.initFly);
      // // console.log(pos, "pos");

      // // getHeigthByLonLat(104.40917673, 35.48126653);
      // // 根据经纬度获取高度
      // function getHeigthByLonLat1(data, len, callback) {
      //   var hrightlist = [];
      //   var positions = [];
      //   data.forEach((element) => {
      //     positions.push(
      //       Cesium.Cartographic.fromDegrees(element[0], element[1])
      //     );
      //   });
      //   var promise = new Cesium.sampleTerrain(
      //     viewer.terrainProvider,
      //     13,
      //     positions
      //   );
      //   promise.then((i) => {
      //     // console.log("getheight", i);
      //     i.forEach((element) => {
      //       hrightlist.push(element);
      //     });
      //     callback(datas, len, hrightlist);
      //     // callback(i[0].height);
      //     // hrightlist.push(i[0].height);
      //   });
      // }

      // callback(heightlist);
    },
    async initFly(flypos) {
      // console.log(flypos, "len, heightlist");

      flypos.forEach((element, index) => {
        element.unshift(index * 1);
       
      });

      // 深克隆原始数据，避免数组被改变
      // const pos = this._.cloneDeep(datas);

      // for (let index = 0; index < pos.length; index++) {
      //   // const element = array[index];
      //   // pos[index].unshift(index * 6);
      //   pos[index].push(heightlist[index].height);
      // }
      // // console.log(pos,"pos");
      // function getflylinedata(pos) {
      //   let points = Cesium.Cartesian3.fromDegreesArrayHeights(pos.flat());

      //   //计算每段比例-形成时间比例
      //   let lengths = [0];
      //   let zlength = 0;
      //   for (let i = 1, l = points.length; i < l; i++) {
      //     let l = Cesium.Cartesian3.distance(points[i - 1], points[i]);

      //     lengths.push(l);
      //     zlength += l;
      //   }
      //   // console.log(lengths, "lengths");
      //   // let rx = zlength / 10;
      //   let t = 0;
      //   lengths.map((len, index) => {
      //     if (index > 0) {
      //       t += len / zlength;
      //       lengths[index] = t;
      //     }
      //   });

      //   //生成样条线  提取采样点
      //   var spline = new Cesium.LinearSpline({
      //     times: lengths,
      //     points: points,
      //   });
      //   // console.log(spline, "spline");
      //   var positions = [];
      //   let n = len;
      //   for (var i = 0; i <= n; i++) {
      //     var cartesian3 = spline.evaluate(i / n);
      //     const cartographic = Cesium.Cartographic.fromCartesian(cartesian3);
      //     const longitudeString = Cesium.Math.toDegrees(cartographic.longitude);
      //     const latitudeString = Cesium.Math.toDegrees(cartographic.latitude);
      //     const heightString = cartographic.height ;
      //     positions.push([longitudeString, latitudeString, heightString]);
      //   }
      //   return positions;
      // }
      // let flypos = [];
      // flypos = getflylinedata(pos);
      // // console.log("flypos", flypos);

      // flypos.forEach((element, index) => {
      //   element.unshift(index * 1);
      // });
      // console.log(pos, "pos==================");
      // console.log(heightlist, "heightlist");
      // heightlist.forEach((element) => {
      //   console.log(element, "element");
      // });
      let that = this;
      let viewer = this.viewer;
      viewer.scene.globe.depthTestAgainstTerrain = false;
      this.viewer.clock.shouldAnimate = true;
      var start = Cesium.JulianDate.fromDate(new Date());
      var stop = Cesium.JulianDate.addSeconds(
        start,
        flypos.length * 1,
        new Cesium.JulianDate()
      );
      // ==================================================新==================================
      const czml = [
        //pocket
        //必须的节点，document
        {
          id: "document",
          name: "CZML Path",
          version: "1.0",
          clock: {
            interval: start.toString() + "/" + stop.toString(),
            // startTime: start.toString(),
            // stopTime: stop.toString(),
            currentTime: start.toString(),
            multiplier: 5,
            // clockRange :Cesium.ClockRange.LOOP_STOP,
          },
        },
        {
          id: "path",
          name: "path with GPS flight data",
          description:
            "<p>Hang gliding flight log data from Daniel H. Friedman.<br>Icon created by Larisa Skosyrska from the Noun Project</p>",
          availability: start.toString() + "/" + stop.toString(),
          path: {
            material: {
              polylineOutline: {
                color: {
                  rgba: [255, 0, 255, 255],
                },
                outlineColor: {
                  rgba: [0, 255, 255, 255],
                },
                outlineWidth: 5,
              },
            },
            width: 8,
            leadTime: 0,
            trailTime: flypos.length *10,
            resolution: 1,
          },
          orientation: {
            unitQuaternion: [
              0.19134171618254486, -0.3314135740355918, 0.4619397662556433,
              0.8001031451912656,
            ],
          },

          // model: {
          //   // show:false,
          //   gltf: "/model/glb/Cesium_Air.glb",
          // },
          position: {
            epoch: start.toString(),
            cartographicDegrees: flypos.flat(),
          },
        },
      ];

      var entityB2;
      var onTickEvent;
      this.dataSources = viewer.dataSources
        .add(Cesium.CzmlDataSource.load(czml))
        .then((ds) => {
          entityB2 = ds.entities.getById("path");
          that.entityB2 = entityB2;
          viewer.trackedEntity = entityB2;
          // console.log(entityB2);
          // const orientation = entityB2.orientation;
          const position = entityB2.position;
          // console.log(position);
          // viewer.scene.preUpdate.addEventListener(setRoamView);
          onTickEvent = viewer.clock.onTick.addEventListener(setRoamView);
          that.onTickEvent = onTickEvent;
          function setRoamView() {
            if (viewer.clock.shouldAnimate === true) {
              // let ori = orientation.getValue(viewer.clock.currentTime); //获取偏向角
              let center = position.getValue(viewer.clock.currentTime); //获取位置
              // console.log(center);
              if (center == undefined) {
                return;
              }
              // 1、由四元数计算三维旋转矩阵
              // var mtx3 = Cesium.Matrix3.fromQuaternion(ori);

              // 2、计算四维转换矩阵：
              // var mtx4 = Cesium.Matrix4.fromRotationTranslation(mtx3, center);

              // 3、计算角度：
              // var hpr = Cesium.Transforms.fixedFrameToHeadingPitchRoll(mtx4);

              // 获取角度（弧度）
              // const headingTemp = hpr.heading;
              // const pitchTemp = hpr.pitch;

              // 调整角度为第一人称
              const heading = Cesium.Math.toRadians(0);
              // const heading = Cesium.Math.toRadians(
              //   Cesium.Math.toDegrees(headingTemp) + 45
              // );
              const pitch = Cesium.Math.toRadians(-40.0);
              // const pitch = Cesium.Math.toRadians(
              //   Cesium.Math.toDegrees(pitchTemp) - 15
              // );
              // 视角高度
              const range = 2000.0;

              viewer.camera.lookAt(
                center,
                new Cesium.HeadingPitchRange(heading, pitch, range)
              );
            }
          }
        });
    },
    exitFly() {
      let viewer = this.viewer;
      let czmldata = viewer.dataSources.getByName("CZML Path");
      // console.log(czmldata)
      czmldata.forEach((element) => {
        viewer.dataSources.remove(element);
      });
      // viewer.dataSources.remove(viewer.dataSources.getByName("CZML Path")[0]);
      viewer.clock.shouldAnimate = false;
      viewer.trackedEntity = undefined;
      this.gohome(3);
    },
  },
};
</script>

<style lang="scss" scoped>
.map {
  width: 100%;
  height: 100%;
  // position: fixed;

  #cesiumContainer {
    width: 100%;
    height: 100%;
    z-index: 1;
    // background-repeat: no-repeat;
  }
}
</style>
